<template>
  <div>
    <h1>json处理工具</h1>
    <br/>
    <!--    <input type="textarea"  style="color: crimson" rows="10" cols="100" v-model="jsonStr"></inputtextarea>-->
    <Input v-model="jsonStr" type="textarea" style="color: crimson;width: 380px" rows="7" cols="30"/>
    <br/>
    <br/>
    <h3>选择要求和的字段名</h3>
    <Input v-model="fieldName1" style="width: 300px" placeholder="选择要求和的字段名" size="small" clearable/>
    <Button type="primary" @click="sumButton()" class="tag-read1" size="small">选择求和</Button>
    <br/>
    <br/>
    <h3 style="color: crimson">字段之和为 : {{ sum }}</h3>
  </div>
</template>
<script>
export default {
  name: 'JsonTools',
  data () {
    return {
      sum: 0,
      fieldName1: '',
      jsonStr: '',
    }
  },
  methods: {
    sumButton () {
      if (this.jsonStr === undefined || this.jsonStr === '' || this.jsonStr.trim() === '') {
        alert('你没填json想干什么')
        return
      }
      var jsonArray
      var json
      try {
        json = JSON.parse(this.jsonStr)
      } catch (e) {
        alert('这个填的不是json')
        return
      }
      try {
        if (Array.isArray(json.data)) {
          jsonArray = json.data
        } else if (Array.isArray(json.data.itemList)) {
          jsonArray = json.data.itemList
        } else {
          alert('json有问题,别浪费时间')
          return
        }
      } catch (e) {
        alert('这个json没有data或者item参数')
        return
      }
      if (this.fieldName1 === undefined || this.fieldName1 === '') {
        alert('你没选字段求什么和')
        return
      }
      if (jsonArray.length === 0) {
        alert('这个数组是空滴')
        return
      }
      if (jsonArray[0][this.fieldName1] === undefined) {
        alert('你选的字段不存在')
        return
      }
      var sumTotal = 0
      jsonArray.forEach(vo =>
          sumTotal = sumTotal + vo[this.fieldName1]
      )
      this.sum = sumTotal
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}

</style>
